import Vue from 'vue'
import Vuex from 'vuex'
import http from '../utils/request.js'
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		token: '',
		username: '',
		nickname:'',
		avatar: '',
		roles: [],
		userInfo: {}
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_USERNAME: (state, username) => {
			state.username = username
		},
		SET_NICKNAME: (state, nickname) => {
			state.nickname = nickname
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
		},
		SET_USERINFO: (state, userInfo) => {
			state.userInfo = userInfo
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles
		}
	},
	actions: {
		getInfo({commit,state},prams) {
			return new Promise((resolve, reject) => {
				http('/admin/sys/user/getInfo','GET',prams).then(response => {
					const {
						data
					} = response
					if (!data) {
						reject('Verification failed, please Login again.')
					}
					const {
						roles,
						username,
						nickname,
						avatar,
						userInfo
					} = data

					if (!roles || roles.length <= 0) {
						reject('getInfo: roles must be a non-null array!')
					}

					commit('SET_USERNAME', username) 
					commit('SET_NICKNAME', nickname) 
					commit('SET_ROLES', roles)
					commit('SET_AVATAR', avatar)
					commit('SET_USERINFO', userInfo)
					resolve(data)
				}).catch(error => {
					reject(error)
				})
			})
		},
	}
})

export default store
